import socket
import typing

from PyQt5.QtCore import QByteArray, QObject, QThread, pyqtSignal
from PyQt5.QtNetwork import QHostAddress, QUdpSocket


class XuanWuUDPReceiver(QThread):
    signalSendReceiveData = pyqtSignal(str)
    def __init__(self, parent: typing.Optional[QObject]) -> None:
        super().__init__(parent=parent)
        # self.__udp_socket_ = QUdpSocket(self)
        self.__udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    
    def SetBindIpAndPort(self, str_ip: str, str_port: str) -> None:
        # print('ip: ' + str_ip + 'port: ' + str_port)
        # self.__udp_socket_.bind(QHostAddress(str_ip), int(str_port))
        self.__udp_socket.bind((str_ip, int(str_port)))
    
    def run(self) -> None:
        while(True):
            data = self.__udp_socket.recv(1024)
            # print(data.decode('utf-8'))
            self.signalSendReceiveData.emit(data.decode('utf-8'))
